﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raven.Client;
using Raven.Client.Document;

namespace RavenAcessLayer
{
    /*
     * Manage context of DocomentStore to operate for only one instance on application
     * 
     * Revison - The implementation of singleton pattern doesnt comtemplate thread-safe 
     *                  NEDDED REVIEW AFTER THIS
     */
    public class DataContext : IDisposable
    {
        public IDocumentStore DocumentStore;

        //Singleton pattern 
        //(uses Connection String Named "RavenDB") from app.confi/web.config
        private static DataContext _db;
        public static DataContext Db
        {
            get
            {
                if (_db == null)
                {
                    _db = new DataContext
                    {
                        DocumentStore = new DocumentStore
                        {
                            ConnectionStringName = "RavenDB",
                        }.Initialize(),
                    };
                    _db._session = _db.DocumentStore.OpenSession();
                }
                return _db;
            }
        }

        //No Public constructor - use Singleton
        private DataContext() { }

        private IDocumentSession _session;
        public IDocumentSession Session
        {
            get
            {
                return this._session;
            }
        }

        public void Dispose()
        {
            this._session.Dispose();
            this.DocumentStore.Dispose();
        }
    }
}
